import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_simple_store_list_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';

import 'event/refresh_smart_home_index_event.dart';

///智能家居门店正在使用的终端页面
class SmartHomeSimpleStoreListPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "SmartHomeSimpleStoreListPage";
  final String shid;
  final String hsn;
  //智能家居与终端绑定关系的id
  final String rasid;
  final bool bindSelect;
  const SmartHomeSimpleStoreListPage({Key key, this.shid, this.hsn, this.rasid, this.bindSelect}):super(key: key);

  @override
  _SmartHomeSimpleStoreListPageState createState() => _SmartHomeSimpleStoreListPageState();

  ///跳转方法
  static Future<SimpleStoreListBean> navigatorPush(
      BuildContext context, String shid, String hsn, String rasid, {bool bindSelect}) {
    return RouterUtils.routeForFutureResult(
      context, SmartHomeSimpleStoreListPage(
      shid: shid,
      hsn: hsn,
      rasid: rasid,
      bindSelect: bindSelect,
    ),
      routeName: SmartHomeSimpleStoreListPage.ROUTER,
    );
  }
}

class _SmartHomeSimpleStoreListPageState extends BaseState<SmartHomeSimpleStoreListPage>{
  SmartHomeViewModel _viewModel;
  SmartHomeStoreDetailViewModel _detailViewModel;
  List<SimpleStoreListBean> data;
  String _currentShid;
  @override
  void initState() {
    super.initState();
    _currentShid = widget?.shid;
    _viewModel = SmartHomeViewModel(this);
    _detailViewModel = SmartHomeStoreDetailViewModel(this);
    _viewModel.getSimpleStoreList("");
    data = new List();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomPadding: false,
          resizeToAvoidBottomInset: false,
          backgroundColor: Color(0xFFF6F7F9),
          body: CommonPackUpKeyboardWidget(
            child: Column(
              children: <Widget>[
                _toTopBarWidget(),
                Expanded(
                  child: _toPlaceHolderWidget(),
                ),
              ],
            ),
          ),
        )
    );
  }

  ///标题栏
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "所属门店",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      backgroundColor: Color(0XFFF6F7F9),
    );
  }


  Widget _toPlaceHolderWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            emptyStatus: value == PlaceHolderStatusType.empty,
            emptyCustomWidget: _defaultEmptyCustomWidget("暂无内容"),
            errorCustomWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
            errorOnClick: () => _viewModel.getSimpleStoreList("",),
            loadingOnClick: () => _viewModel.getSimpleStoreList("",),
            child: child,
          );
        },
        child: _toBodyWidget());
  }

  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_empty_white.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg??"暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        )
      ],
    );
  }

  Widget _toBodyWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.simpleStoreListValueNotifier,
        builder: (BuildContext context, List<SimpleStoreListBean> storeList, Widget child){
          if(storeList != null){
            data.clear();
            data.addAll(storeList);
          }
          return _toListWidget();
        }
    );
  }

  ///图片展示栏
  Widget _toListWidget(){
    return ListView.separated(
      padding: EdgeInsets.only(top: 0, bottom: 50),
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        return _toListItemWidget(context, index,);
      },
      separatorBuilder: (BuildContext context, int index){
        return SizedBox();
      },
      itemCount: data?.length??0,
    );
  }

  ///item
  Widget _toListItemWidget(BuildContext context, int index, ){
    SimpleStoreListBean itemBean = data?.elementAt(index);
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()  async{
        if(itemBean?.shid == _currentShid){
          return;
        }
        if(widget?.bindSelect??false){
          RouterUtils.pop(context, result: itemBean);
        }else{
          bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: "确定更换所属门店？",
            cancelText: "取消",
            confirmText: "更换",
            confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            cancelBgColor: Color(0xFFF6F7F9),
            titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            widgetBgColor: Colors.white,
          );
          if (result ?? false) {
            _detailViewModel.terminalChangeSmartHome(context, widget?.hsn, widget?.rasid, itemBean?.shid, () {
              RouterUtils.pop(context);
            });
          }
        }
      },
      child: Container(
        height: 64,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        alignment: Alignment.centerLeft,
        color: Colors.white,
        child:  _toContentWidget(index, itemBean),
      ),
    );
  }

  Widget _toContentWidget(int index, SimpleStoreListBean itemBean) {
    bool isCurrent = (itemBean?.shid == _currentShid);
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          itemBean?.getTitle(),
          style: TextStyle(
            fontSize: 14,
            color: isCurrent?ThemeRepository.getInstance().getPrimaryColor_1890FF():ThemeRepository.getInstance().getCardBgColor_21263C(),
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        SizedBox(height: 3,),
        Text(
          itemBean?.getShowAddress(),
          style: TextStyle(
            fontSize: 12,
            color: Color(0XFF8B93A5),
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }

}